package com.hdd.hll.quartz.job;

import com.alibaba.fastjson.JSON;
import com.hdd.hll.common.response.Result;
import com.hdd.hll.common.utils.AesEncryptUtils;
import com.hdd.hll.common.utils.OpenApiLogUtil;
import com.hdd.hll.common.utils.StringUtils;
import com.hdd.hll.modules.order.web.dto.PlanInfoDto;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 调拨单推送Job实现类
 *
 * @author jw
 */
@Slf4j
@Component
public class PushOrderJob implements Job {
    @Autowired
    private RestTemplate restTemplate;

    @Value("${jd.api.url}")
    private String apiUrl;

    @Value("${api.path.suffix.plan.syncPlanInfo}")
    private String syncPlanInfoPath;

    @Override
    public void execute(JobExecutionContext context) {
        Map map = context.getJobDetail().getJobDataMap();
        Set<Map.Entry<String, String>> entrys = map.entrySet();
        for (Map.Entry<String, String> entry : entrys) {
            // 渠道参数，执行相应的业务流程
            log.info("执行JD调拨单信息同步接口推送任务，入参：{}", entry.getValue());
            syncPlanInfo(JSON.parseObject(entry.getValue(), PlanInfoDto.class));
        }
    }


    public Result<String> syncPlanInfo(PlanInfoDto planInfoDto) {
        StringBuilder dataValidateResult = paramValid(planInfoDto);

        Result<String> result = new Result<>();
        if (!org.apache.commons.lang3.StringUtils.isBlank(dataValidateResult)) {
            result.setCode("500");
            result.setMsg(dataValidateResult.toString());
            OpenApiLogUtil.logResponse(result);
            return result;
        }
        Result<String> decryptResp = null;

        try {
            String encryptJsonString = restTemplate.postForObject(apiUrl + syncPlanInfoPath, AesEncryptUtils.encrypt(JSON.toJSONString(planInfoDto)), String.class);
            decryptResp = JSON.parseObject(AesEncryptUtils.decrypt(encryptJsonString), Result.class);
            log.info("请求JD矿区调拨单信息同步接口，Msg：{}", decryptResp);


        } catch (Exception e) {
            log.error("请求JD矿区调拨单信息同步接口异常，Msg：{}", e.getMessage());
            if (Objects.isNull(decryptResp)) {
                decryptResp = new Result<>();
            }
            decryptResp.setCode("500");
            decryptResp.setMsg(String.format("请求JD矿区调拨单信息同步接口异常，Msg：%s", e.getMessage()));

        }
        OpenApiLogUtil.logResponse(decryptResp);
        return decryptResp;
    }

    /**
     * 调拨单信息同步接口参数校验
     *
     * @param planInfoDto
     * @return
     */
    private StringBuilder paramValid(PlanInfoDto planInfoDto) {
        StringBuilder dataValidateResult = new StringBuilder();
        if (StringUtils.isNullOrEmpty(planInfoDto.getMiningDistrictId())) {
            dataValidateResult.append("矿区编号获取异常：miningDistrictId must not be null or empty；");
        }
        if (StringUtils.isNullOrEmpty(planInfoDto.getMiningDistrict())) {
            dataValidateResult.append("矿区名称获取异常：miningDistrict must not be null or empty；");
        }
        if (StringUtils.isNullOrEmpty(planInfoDto.getCustomerId())) {
            dataValidateResult.append("客户编号获取异常：customerId must not be null or empty；");
        }
        if (StringUtils.isNullOrEmpty(planInfoDto.getCustomerName())) {
            dataValidateResult.append("客户名称获取异常：customerName must not be null or empty；");
        }
        if (StringUtils.isNullOrEmpty(planInfoDto.getCoaltypeID())) {
            dataValidateResult.append("煤种编号获取异常：coaltypeID must not be null or empty；");
        }
        if (StringUtils.isNullOrEmpty(planInfoDto.getCoaltypeName())) {
            dataValidateResult.append("煤种名称获取异常：coaltypeName must not be null or empty；");
        }
        if (StringUtils.isNullOrEmpty(planInfoDto.getWeight())) {
            dataValidateResult.append("调拨量获取异常：weight must not be null,empty or zero；");
        }
        if (StringUtils.isNullOrEmpty(planInfoDto.getPickupTimeStart())) {
            dataValidateResult.append("提货起始时间获取异常：pickupTimeStart must not be null or empty；");
        }
        if (StringUtils.isNullOrEmpty(planInfoDto.getPickupTimeEnd())) {
            dataValidateResult.append("提货终止时间获取异常：pickupTimeEnd must not be null or empty；");
        }
        if (Objects.isNull(planInfoDto.getStatus())) {
            dataValidateResult.append("状态获取异常：status must not be null；");
        }
        return dataValidateResult;
    }


}
